import {
  Component,
  OnInit,
  Injector,
  ViewChild,
  ViewChildren,
  ElementRef,
  QueryList,
  OnDestroy,
} from '@angular/core';
import { map, tap } from 'rxjs/operators';
import { ListBase } from 'app/modules/base/list-base';
import { ToasterService } from 'app/modules/share/services/toaster.service';
import { Personnel, PersonnelService, UserStatus } from '../../services/personnel.service';
import { MySelection } from 'app/modules/base/selection';
import { HttpErrorResponse } from '@angular/common/http';
import { MatDialog } from '@angular/material';
import { SynchronizeComponent } from '../synchronize/synchronize.component';
import { LoginService } from '../../../login/services/login.service';

@Component({
  selector: 'm-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
})
export class ListComponent extends ListBase implements OnInit {
  
  constructor(
    private injector: Injector,
    private personnelManager: PersonnelService,
    public dialog: MatDialog,
    public loginService: LoginService
  ) {

    
    super(injector);
    this.loginService.User$.subscribe(res=>{
      if(res.is_super){
    //查询当前同步状态
    this.personnelManager.syncStatus().subscribe((res:any) =>{
      if(res.code === 0 && res.message === 0){
        const dialogRef = this.dialog.open(SynchronizeComponent, {
          width: '300px',
          disableClose: true,
          data: { status: res.message}
        });
      }
    })
      } 
    })
  }
  is_super:boolean;
  issuper: boolean;
  user$ = this.loginService.User().then(user=>{
    this.issuper= user.is_super;
  });
  UserStatus = UserStatus;
  Sortable = [
    'full_name',
    'job_number',
    'utype',
    'status',
    'update_admin_username',
    'updated_at',
    'created_at',
  ];
  
  result$ = this.getList<Personnel>().pipe(tap((result) => this.selectAllCheck(result.list)));

  selection = new MySelection<Personnel>('id');
  ngOnInit() {
  }

  async delete(ps: Personnel[]) {
    if ((await this.sweet.confirm(`确定要删除[${ps.map(p => p.full_name).join(',')}]吗`)).dismiss) {
      return;
    }
    await this.personnelManager.delete(ps.map(p => p.id));
    this.reload();
  }
  async disable(uid: number[]) {
    if ((await this.sweet.confirm('确定要停用吗')).dismiss) {
      return;
    }
    await this.personnelManager.batch('status', UserStatus.Disable, uid);
    this.reload();
  }
  async enable(uid: number[]) {
    if ((await this.sweet.confirm('确定要启用吗')).dismiss) {
      return;
    }
    await this.personnelManager.batch('status', UserStatus.Enable, uid);
    this.reload();
  }
  async import() {
    const input = document.createElement('input');
    input.type = 'file';
    input.click();
    await new Promise(resolve => input.addEventListener('change', resolve, { once: true }));
    const data = new FormData();
    data.set('file', input.files[0]);
    try {
      await this.personnelManager.import(data);
    } catch (err) {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 406) {
          const error = err.error as {
            illegal_lines: number[];
            repeat_lines: number[];
          };
          if (error.illegal_lines) {
            this.toaster.warn(
              '导入失败！第' + error.illegal_lines.join(',') + '行登录账号格式有误',
            );
          } else if (error.repeat_lines) {
            this.toaster.warn('导入失败！第' + error.repeat_lines.join(',') + '行登录账号重复');
          }
        }
      }
      return;
    }
    this.toaster.success('导入成功');
    this.reload();
  }



  openDialog(): void {
    const dialogRef = this.dialog.open(SynchronizeComponent, {
      width: '350px',
      disableClose: true,
      data: {status: -1}
    });
  }


}
